<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      //   const a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
      //   let limit = []
      //   let parr = a.map(
      //     item =>
      //       new Promise((resolve, reject) => {
      //         setTimeout(() => {
      //           reject(item)
      //         }, item * 1000)
      //       })
      //   )
      //   const initLimit = () => {
      //     let i = 0
      //     while (i !== 3) {
      //       i++
      //       limit.push(parr.shift())
      //     }
      //   }
      //   const startLimit = async () => {
      //     for (let i = 0; i < limit.length; i++) {
      //       const item = limit[i]
      //       try {
      //         let a = await item
      //         console.log('zz')
      //       } catch (e) {
      //         console.log(e)
      //       }
      //       parr.length > 0 && limit.push(parr.shift())
      //       //   item.then(res => {
      //       //     console.log(res)
      //       //     limit.push(parr.shift())
      //       //   })
      //     }
      //   }
      //   initLimit()
      //   startLimit()
      const a = new Promise(resolve => {
        console.log('zzz')
        resolve('xxx')
      })
      const asyncPool = async (poolLimit, array, iteratorFn) => {
        const resultList = []
        const executing = []
        for (const item of array) {
          console.log('循环', item)
          const p = Promise.resolve().then(() => {
            console.log('初始化', item)
            return iteratorFn(item, array)
          })
          resultList.push(p)
          if (poolLimit <= array.length) {
            const e = p.then(() => {
              return executing.splice(executing.indexOf(e), 1)
            })
            executing.push(e)
            if (executing.length >= poolLimit) {
              console.log('运行Promise.race')
              await Promise.race(executing)
            }
          }
        }
        return Promise.all(resultList)
      }
    </script>
  </body>
</html>
